// 百度云语音识别工具类
const config = {
  apiKey: 'koz6PiK2dHEw6MUZXbt8hEUB',  // 替换为你的API Key
  secretKey: 'x5LTTmfVLVP6dQdXhrpE2MXKQuPi6nIF',  // 替换为你的Secret Key
  grantType: 'client_credentials'
}

// 获取百度云Access Token
export function getAccessToken() {
  return new Promise((resolve, reject) => {
    const url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + config.apiKey + '&client_secret=' + config.secretKey
    
    uni.request({
      url: url,
      method: 'POST',
      success: (res) => {
        console.log('获取AccessToken响应:', res);
        if (res.statusCode === 200 && res.data.access_token) {
          // 缓存token，有效期为30天
          uni.setStorageSync('baidu_asr_token', res.data.access_token)
          uni.setStorageSync('baidu_asr_token_expires', Date.now() + res.data.expires_in * 1000)
          resolve(res.data.access_token)
        } else {
          reject('获取AccessToken失败')
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 检查并获取有效的AccessToken
export async function checkAndGetToken() {
  const token = uni.getStorageSync('baidu_asr_token')
  const expires = uni.getStorageSync('baidu_asr_token_expires')
  
  // 如果token不存在或已过期，则重新获取
  if (!token || Date.now() > expires - 3600000) { // 提前1小时刷新
    return await getAccessToken()
  }
  return token
}

// 语音识别核心函数
export function recognizeSpeech(audioData, format = 'pcm', rate = 16000) {
  return new Promise(async (resolve, reject) => {
    try {
      const token = await checkAndGetToken()
      const url = `https://vop.baidu.com/server_api?cuid=weixinmini&token=${token}`
      
      // 音频数据Base64编码
      const base64Data = uni.arrayBufferToBase64(audioData)
      
      uni.request({
        url: url,
        method: 'POST',
        header: {
          'Content-Type': 'application/json'
        },
        data: {
          format: format,
          rate: rate,
          channel: 1,
          cuid: 'weixinmini',
          token: token,
          speech: base64Data,
          len: audioData.byteLength
        },
        success: (res) => {
          if (res.statusCode === 200) {
            if (res.data.err_no === 0) {
              resolve(res.data.result[0])
            } else {
              reject(`识别失败: ${res.data.err_msg}`)
            }
          } else {
            reject(`请求失败: ${res.statusCode}`)
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    } catch (error) {
      reject(error)
    }
  })
}
